package com.examsys.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import com.examsys.po.ExamDetail;
import com.examsys.po.ExamMain;
import com.examsys.po.Paper;
import com.examsys.po.PaperDetail;
import com.examsys.po.PaperUserGroup;
import com.examsys.service.ExamMainService;
import com.examsys.service.Main;
import com.examsys.service.PaperService;
import com.examsys.service.PaperUserGroupService;
/**
 * 考试者可参与考试的试卷面板
 * @author mashiqiong
 *
 */
public class UserPaperListPanel extends JPanel {
	private JTable table;

	/**
	 * Create the panel.
	 */
	public UserPaperListPanel() {
		
		JScrollPane scrollPane = new JScrollPane();
		
		JButton button = new JButton("立即参加考试");
		//创建按钮监听器对象
		ActionListener takeAnExamActionListener = new TakeAnExamActionListener();
		button.addActionListener(takeAnExamActionListener);//按钮绑定监听器对象
		
		GroupLayout groupLayout = new GroupLayout(this);
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
							.addGap(9))
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(button)
							.addContainerGap(335, Short.MAX_VALUE))))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 223, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(button)
					.addContainerGap(26, Short.MAX_VALUE))
		);
		
		table = new JTable();
		scrollPane.setViewportView(table);
		setLayout(groupLayout);
		initDatas();
	}
	
	/**
	 * 初始化表格数据的方法
	 */
	private void initDatas(){
		
		Object[][] datas = new Object[][] {
			{null, null, null, null, null, null, null, null, null, null, null, null},
			{null, null, null, null, null, null, null, null, null, null, null, null},
			{null, null, null, null, null, null, null, null, null, null, null, null},
			{null, null, null, null, null, null, null, null, null, null, null, null},
			{null, null, null, null, null, null, null, null, null, null, null, null},
			{null, null, null, null, null, null, null, null, null, null, null, null},
			{null, null, null, null, null, null, null, null, null, null, null, null},
			{null, null, null, null, null, null, null, null, null, null, null, null},
		};
		
		String[] columnNames = new String[] {
			"编号", "管理员", "试卷名称", "开始考试时间", "结束考试时间", "考试总时间", "考试总分数", "提交时间", "公布成绩时间", "题目顺序", "试卷状态", "备注"
		};
		
		try {
			//从容器中获取业务逻辑层对象
			PaperUserGroupService paperUserGroupService=Main.lookUp("paperUserGroupService");
			PaperUserGroup paperUserGroup1=new PaperUserGroup();
			paperUserGroup1.setUserGroups(Main.users.getUserGroups());
			List<PaperUserGroup> paperUserGroupList = paperUserGroupService.getList(paperUserGroup1);
			
			String inIds="";
			for(PaperUserGroup paperUserGroup:paperUserGroupList){
				inIds+=paperUserGroup.getPaper().getId()+",";
			}
			
			if(inIds.length()>0){
				inIds=inIds.substring(0, inIds.length()-1);//去除最后一个逗号
			}
			
			//从容器中获取业务逻辑层对象
			PaperService paperService=Main.lookUp("paperService");
			List<Paper> list = paperService.getList(inIds);//调用业务逻辑层对象的 方法获取数据
			
			if(list.size()>0){
				datas = new Object[list.size()][12];
				for(int i=0;i<list.size();i++){
					Paper paper = list.get(i);
					
					datas[i][0]=paper.getId();//编号
					datas[i][1]=paper.getAdmin().getUser_name();//管理员
					datas[i][2]=paper.getPaper_name();//试卷名称
					datas[i][3]=paper.getStart_time();//开始考试时间
					datas[i][4]=paper.getEnd_time();//结束考试时间
					datas[i][5]=paper.getPaper_minute();//考试总时间
					datas[i][6]=paper.getTotal_score();//考试总分数
					datas[i][7]=paper.getPost_date();//提交时间
					datas[i][8]=paper.getShow_score();//公布成绩时间
					datas[i][9]=paper.getQorder();//题目顺序
					datas[i][10]=paper.getStatus().equals("1")?"开放":"不开放";//试卷状态
					datas[i][11]=paper.getRemark();//备注
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		table.setModel(new DefaultTableModel(datas,columnNames));
	}
	
	/**
	 * 
	 * 立即考试按钮监听器类
	 * @author edu-1
	 *
	 */
	private class TakeAnExamActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			RowSorter<? extends TableModel> rowSorter = table.getRowSorter();//拿到行排序器
			TableModel model = rowSorter.getModel();//表格的数据模型
			int[] selectedRows = table.getSelectedRows();//当前选择行号数组
			
			if(selectedRows!=null&&selectedRows.length>0&&selectedRows.length==1){
				int index = rowSorter.convertRowIndexToModel(selectedRows[0]);//转换成真正的行号
				Integer id = (Integer)model.getValueAt(index, 0);//获取选中第一列数据
				
				//创建实体类对象，并构建查询条件
				ExamMain examMain1=new ExamMain();
				Paper paper1=new Paper();//创建试卷对象
				paper1.setId(id);//设置编号
				examMain1.setPaper(paper1);//关联当前选中的试卷
				examMain1.setUsers(Main.users);//关联当前登录的用户
				examMain1.setStatus("1");//考试中的试卷
				try {
					ExamMainService examMainService = Main.lookUp("examMainService");
					List<ExamMain> list = examMainService.getList(examMain1);//通过编号找到对象
					
					ExamMain examMain=null;//声明实体类对象
					if(list.size()>0){
						examMain=list.get(0);//拿出先前已经有的答题卡
					}
					
					if(examMain==null){//如果还没有答题卡，则创建答题卡及其明细
						
						PaperService paperService=Main.lookUp("paperService");
						Paper paper2 = paperService.get(id);
						ExamMain examMain2=new ExamMain();
						
						//当前用户考试开始时间的毫秒数
						long currentTimeMillis = System.currentTimeMillis();
						
						examMain2.setStart_time(new Timestamp(currentTimeMillis));//开始考试时间
						
						//当前用户考试结束时间的毫秒数
						long time = paper2.getPaper_minute()*60*1000+currentTimeMillis;
						
						examMain2.setEnd_time(new Timestamp(time));//结束考试时间
						examMain2.setPaper(paper2);
						examMain2.setUsers(Main.users);
						examMain2.setStatus("1");//考试状态,1考试中，2已经交卷，3已经评分
						examMain2.setIp("");
						
						List<ExamDetail> examDetailList=new ArrayList<ExamDetail>();
						List<PaperDetail> paperDetails = paper2.getPaperDetails();
						for(PaperDetail pd:paperDetails){//处理明细
							ExamDetail examDetail3=new ExamDetail();
							examDetail3.setExamMain(examMain2);
							examDetail3.setQuestion(pd.getQuestion());
							examDetail3.setStatus("0");
							examDetailList.add(examDetail3);
						}
						examMain2.setExamDetails(examDetailList);//关联对象
						
						boolean flag = examMainService.add(examMain2);//保存主答题卡及其明细
						if(flag){//如果创建成功，则拿出来给考试者答题
							list = examMainService.getList(examMain1);//通过试卷编号及用户去找到答题卡
							if(list.size()>0){
								examMain=list.get(0);//拿出已经有的试卷
							}
						}
					}
					
					if(examMain!=null){
						//创建添加试题对话框对象
						TakeAnExamDialog takeAnExamDialog=new TakeAnExamDialog();
						takeAnExamDialog.setExamMain(examMain);//把实体类对象传给对话框用于显示与修改
						takeAnExamDialog.setVisible(true);
					}else{
						MessageDialog messageDialog=new MessageDialog();
						messageDialog.setMsg("试卷参数有误，答题卡未能成功创建");
						messageDialog.setVisible(true);
					}
					initDatas();//刷新表格数据
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
			}
		}
	}
}
